<?php

class AuthController extends Controller {

	public function __construct() {
		parent::__construct(__CLASS__);
	}

	public function indexAction() {
		$this->layout('simple_layout');
		$this->rend('index');
	}

	public function loginAction() {
		$email = addslashes(requestPost('email'));
		$password = requestPost('password');

		if (empty($email) || empty($password)) {
			setFlash('error', 'Please enter your email or password.');
			redirect(url('auth/index'));
		}

		$sql = "SELECT `id`,`nick`,`password` FROM user WHERE `email`='{$email}'";

		$this->db = DB::open('reading');

		$result = $this->db->query($sql);

		if (isset($result[0]) && isset($result[0]['password']) && sha1($password) == $result[0]['password']) {
			$_SESSION['reading_user_id'] = $result[0]['id'];
			$_SESSION['reading_user_nick'] = $result[0]['nick'];

			setFlash('success', 'Login Successful!');
			redirect(url('home/index'));
		} else {
			setFlash('error', 'Login Failed!' . sha1($password) . $result[0]['password']);
			redirect(url('auth/index'));
		}
	}

	public function logoutAction() {
		unset($_SESSION['reading_user_id'], $_SESSION['reading_user_nick']);
		session_destroy();
		redirect(url('auth/index'));
	}

}
